<template>
    <el-card shadow="never">
        <store-progress v-model="step" />
    </el-card>
    <el-card shadow="never" style="margin: 16px 0">
        <div class="content">
            <div class="storeTips">
                <store-tips :type="4" />
            </div>
            <div class="line"></div>
            <div v-show="step === 1" class="msg">
                <div class="title">店铺基本信息</div>
                <el-form
                    ref="storeBaseFormRef"
                    :model="storeBaseForm"
                    :rules="storeBaseFormRules"
                    label-width="auto"
                    :disabled="disabledFunc">
                    <el-form-item v-if="disabledFunc" label="客易达店铺ID" required>
                        <el-input v-model="shop_id" />
                    </el-form-item>
                    <el-form-item label="店铺名称" prop="name">
                        <el-input v-model="storeBaseForm.name" placeholder="请输入店铺名称" />
                    </el-form-item>
                    <el-form-item label="店铺描述" prop="desc">
                        <el-input v-model="storeBaseForm.desc" type="textarea" placeholder="请输入店铺描述" />
                    </el-form-item>
                    <el-form-item label="店铺logo" prop="logo">
                        <store-upload v-model="storeBaseForm.logo" />
                    </el-form-item>
                    <el-form-item label="用户数据同步" prop="cust_sync">
                        <div>
                            <el-switch
                                v-model="storeBaseForm.cust_sync"
                                class="ml-2"
                                :active-value="1"
                                :inactive-value="2" />
                            <span style="font-size: 12px; padding-left: 4px"
                                >开启后，商户的游客信息和注册用户信息将实时同步到客易达scrm</span
                            >
                        </div>
                        <div v-show="storeBaseForm.cust_sync == 1" class="cust_sync">
                            <el-checkbox
                                v-model="storeBaseForm.points_sync"
                                class="cust_sync_points_checkbox"
                                :true-label="1"
                                :false-label="2"
                                size="large" />
                            <div class="cust_sync_points">
                                <div>
                                    同步用户初始积分。（适用场景：商家希望整合用户在各个渠道的积分，保持积分一致）
                                </div>
                                <div>
                                    若用户存在于多渠道，合并用户时，默认积分累加规则计算初始积分。<span
                                        @click="handlerPoints"
                                        >初始积分规则设置</span
                                    >
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="订单数据同步" prop="order_sync">
                        <el-switch
                            v-model="storeBaseForm.order_sync"
                            class="ml-2"
                            :active-value="1"
                            :inactive-value="2" />
                        <span style="font-size: 12px; padding-left: 4px"
                            >开启后，商户全部店铺的订单信息将实时同步到客易达scrm</span
                        >
                    </el-form-item>
                    <el-form-item label="商品数据同步" prop="product_sync">
                        <el-switch
                            v-model="storeBaseForm.product_sync"
                            class="ml-2"
                            :active-value="1"
                            :inactive-value="2" />
                        <span style="font-size: 12px; padding-left: 4px"
                            >开启后，商户的商品库将实时同步到客易达scrm</span
                        >
                    </el-form-item>
                    <el-form-item label="行为数据同步" prop="behavior_sync">
                        <el-switch
                            v-model="storeBaseForm.behavior_sync"
                            class="ml-2"
                            :active-value="1"
                            :inactive-value="2" />
                        <span style="font-size: 12px; padding-left: 4px"
                            >开启后，用户行为数据将实时同步到客易达scrm</span
                        >
                    </el-form-item>
                    <el-form-item label="积分变动通知" prop="point_sync">
                        <el-switch
                            v-model="storeBaseForm.points_notice"
                            class="ml-2"
                            :active-value="1"
                            :inactive-value="2" />
                        <span style="font-size: 12px; padding-left: 4px"
                            >开启后，用户积分变动将实时同步到客易达scrm</span
                        >
                    </el-form-item>
                    <el-form-item label="订阅通知" prop="subscribe_switch">
                        <el-switch
                            v-model="storeBaseForm.subscribe_switch"
                            class="ml-2"
                            :active-value="1"
                            :inactive-value="2" />
                        <span style="font-size: 12px; padding-left: 4px"
                            >开启后，可订阅来自客易达scrm的客户、订单、行为变动等事件通知</span
                        >
                    </el-form-item>
                    <el-form-item v-if="storeBaseForm.subscribe_switch == 1" label="订阅URL" prop="subscribe_url">
                        <div style="display: flex">
                            <el-input
                                v-model="storeBaseForm.subscribe_url"
                                :style="{ flex: '1' }"
                                placeholder="请输入订阅URL" />
                            <span
                                class="test"
                                style="font-size: 12px; padding-left: 12px"
                                :class="{ disabled: !storeBaseForm.subscribe_url }"
                                @click="test"
                                >联通测试</span
                            >
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <div v-show="step === 2" class="finishBox">
                <el-icon :style="{ fontSize: '60px' }" color="#60B900">
                    <CircleCheckFilled />
                </el-icon>
                <div v-if="type != 'look'">店铺创建成功</div>
                <div class="tag">您的客易达店铺ID为：{{ shop_id }} <span @click="copy(shop_id)">复制</span></div>
                <div v-if="open_platform == 1" class="tag">
                    请前往设置与开发去开启开发者功能 <span @click="toSetting">去配置</span>
                </div>
            </div>
        </div>
    </el-card>
    <div class="footer_button">
        <el-button v-if="step === 1" type="primary" @click="nextStep">下一步</el-button>
        <template v-else>
            <el-button @click="preStep">上一步</el-button>
            <el-button type="primary" @click="done">完成</el-button>
        </template>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import router from '@/router';
import { useRoute } from 'vue-router';
import { getStoreList, addStore, testUrl, getStoreDetail } from '@/api/ecommerce/storeManage';
import storeProgress from '../components/storeProgress.vue';
import storeTips from '../components/storeTips.vue';
import storeUpload from '../components/storeUpload.vue';

import lodash from 'lodash';
import useClipboard from 'vue-clipboard3';

import type { FormInstance, FormRules } from 'element-plus';

const routers = useRoute();
const { toClipboard } = useClipboard();
const { type } = routers.query;

const storeBaseFormRef = ref<FormInstance>();
const step = ref<number>(1);
const shop_id = ref<string>('');
const open_platform = ref<string | number>('');
const isUrlRight = ref<boolean>(false);

const validateHttp = (rule: any, value: any, callback: any) => {
    if (value === '') {
        isUrlRight.value = false;
        callback(new Error('请输入订阅URL'));
    } else {
        const reg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
        if (reg.test(value)) {
            isUrlRight.value = true;
            callback();
        } else {
            isUrlRight.value = false;
            callback(new Error('请输入带有http或https的正确URL'));
        }
    }
};

type storeBaseFormType = {
    name: string;
    desc: string;
    logo: string;
    cust_sync: number;
    order_sync: number;
    product_sync: number;
    behavior_sync: number;
    subscribe_switch: number;
    subscribe_url: string;
    points_sync: number;
    points_notice: number;
};

const storeBaseForm = reactive<storeBaseFormType>({
    name: '',
    desc: '',
    logo: '',
    cust_sync: 1,
    order_sync: 1,
    product_sync: 1,
    behavior_sync: 1,
    subscribe_switch: 2,
    subscribe_url: '',
    points_sync: 1,
    points_notice: 1
});
const storeBaseFormRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入店铺名称', trigger: 'change' }],
    desc: [{ required: false, message: '请输入店铺描述', trigger: 'change' }],
    logo: [{ required: false, message: '请上传店铺logo', trigger: 'change' }],
    subscribe_url: [
        { required: true, message: '请输入订阅URL', trigger: 'change' },
        { validator: validateHttp, trigger: 'blur' }
    ]
});

const nextStep = async () => {
    // 查看下一步时，不调用接口
    if (type == 'look') {
        if (step.value < 2) {
            step.value++;
            return;
        }
    }
    if (!storeBaseFormRef.value) return;
    await storeBaseFormRef.value.validate(async (valid: any): Promise<void> => {
        if (valid) {
            if (await addStoreCom()) {
                if (step.value < 2) step.value++;
            }
        }
    });
};

const preStep = () => {
    if (step.value > 1) step.value--;
};

const done = () => {
    const path = '/ecommerce/storeManage/list';
    router.push(path);
};

const addStoreCom = async (): Promise<boolean> => {
    let params = lodash.cloneDeep(storeBaseForm);
    const source = Number(routers.query.source);
    const extr = {
        // external_shop_id: '',
        source
        // sync_type: 1,
        // cust_sync: 1,
        // order_sync: 1,
        // product_sync: 1,
        // behavior_sync: 1,
        // subscribe_switch: 2,
        // subscribe_url: ''
    };
    params = Object.assign({}, params, extr);
    // 当订阅通知关闭时，订阅URL置为空值
    if (params.subscribe_switch == 2) {
        params.subscribe_url = '';
    }
    // 当用户数据同步关闭时，同步用户初始积分关闭
    if (params.cust_sync == 2) {
        params.points_sync = 2;
    }
    const { shop_id: shop_id_, open_platform: open_platform_ } = await addStore(params);
    if (shop_id_) {
        shop_id.value = shop_id_.toString();
        open_platform.value = open_platform_;
        return true;
    } else {
        return false;
    }
};

const copy = async (val: string) => {
    try {
        await toClipboard(val);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

const toSetting = () => {
    const path = '/channelconfig/developConfiguration/basicConfiguration';
    router.push(path);
};

const handlerPoints = () => {
    const path = '/member/pointsManage/pointsSettings';
    router.push(path);
};

const test = async () => {
    const { subscribe_url: url } = storeBaseForm;
    if (url) {
        const params = { url };
        const res = await testUrl(params);
        if (res) {
            ElMessage.success('联通测试成功！');
        }
    }
};

const height = computed(() => {
    const clientHeight = document.documentElement.clientHeight;
    return `${clientHeight - 380}px`;
});

/**
 * 是否禁用表单
 */
const disabledFunc = computed(() => {
    return type == 'look';
});

/**
 * 获取店铺详情
 */
const getStoreDetailsFunc = async () => {
    const data = await getStoreDetail({ retail_shop_id: routers.query.shop_id });
    const { retail_shop_id, name, desc, logo, retail_shop_config } = data;
    shop_id.value = retail_shop_id;
    storeBaseForm.name = name;
    storeBaseForm.desc = desc;
    storeBaseForm.logo = logo;
    const retail_shop_config_data = retail_shop_config;
    const {
        cust_sync,
        points_sync,
        order_sync,
        product_sync,
        behavior_sync,
        points_notice,
        subscribe_switch,
        subscribe_url
    } = retail_shop_config_data;
    storeBaseForm.cust_sync = cust_sync;
    storeBaseForm.points_sync = points_sync || 1;
    storeBaseForm.order_sync = order_sync;
    storeBaseForm.product_sync = product_sync;
    storeBaseForm.behavior_sync = behavior_sync;
    storeBaseForm.points_notice = points_notice;
    storeBaseForm.subscribe_switch = subscribe_switch;
    storeBaseForm.subscribe_url = subscribe_url;
};

onMounted(() => {
    if (type == 'look') {
        getStoreDetailsFunc();
    }
});
</script>
<style scoped lang="scss">
.content {
    display: flex;
    justify-content: space-between;
    height: calc(100vh - 339px);

    .cust_sync {
        display: flex;
        line-height: 20px;

        .cust_sync_points_checkbox {
            margin-top: -10px;
        }

        .cust_sync_points {
            padding-left: 6px;
            width: 100%;
            font-size: 14px;

            span {
                color: #ff6b00;
                cursor: pointer;
            }
        }
    }

    .storeTips {
        flex: 1;
    }

    .line {
        width: 0;
        border-left: 1px dashed #eee;
        margin: 0 20px 0 8px;
    }

    .msg {
        overflow: auto;
        flex: 1;
        height: v-bind(height);
        box-sizing: border-box;
        padding-left: 10px;
        padding-right: 36px;

        .title {
            border-left: 3px solid #ff6b00;
            padding-left: 8px;
            margin: 10px 0 24px;
        }

        .test {
            &:hover {
                cursor: pointer;
                color: #ff6b00;
            }
        }
    }

    .finishBox {
        flex: 1;
        height: 500px;
        padding-left: 30px;
        padding-bottom: 100px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        & > div {
            line-height: 2;
            font-size: 12px;
            color: #555;
        }

        .tag {
            span {
                color: #ff6b00;

                &:hover {
                    cursor: pointer;
                }
            }
        }
    }
}

.next {
    display: flex;
    justify-content: flex-end;
}

.finished {
    display: flex;
    justify-content: flex-end;
}

.footer_button {
    text-align: center;
    background-color: #fff;
    padding: 16px 24px;
    margin: 0 -16px -16px;
    border-top: 1px solid #eaeaea;
}
</style>
